package com.chasing.baseframe.service.download;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class DownloadWork extends Worker {
    private final Context mContext;
    private static String mDownUrl;

    private static String mTitle;
    private static String mName;

    public DownloadWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        mContext = context;
    }

    public static void startWork(Context context, String downUrl, String title, String name) {
        mDownUrl = downUrl;
        mTitle = title;
        mName = name;
        WorkRequest uploadWorkRequest = new OneTimeWorkRequest.Builder(DownloadWork.class).build();
        WorkManager.getInstance(context).enqueue(uploadWorkRequest);
    }

    @NonNull
    @Override
    public Result doWork() {
        try {
            LoadManager loadManager = LoadManager.getInstance();
            loadManager.addRequest(mContext, mDownUrl, mTitle, mName);
            loadManager.registerContentObserver(mContext);
            loadManager.enqueue();
            return Result.success();
        } catch (Exception e) {
            return Result.retry();
        }
    }

    public static class DownloadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (context == null || intent == null) return;
            String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
                        long taskId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                        LoadManager.getInstance().onDownloadComplete(context, taskId);
                        break;

                    case DownloadManager.ACTION_NOTIFICATION_CLICKED:
                        break;
                }
            }
        }
    }

}
